package com.splic.web.controller.product;

import java.util.*;
import java.util.stream.Collectors;

import com.splic.common.utils.StringUtils;
import com.splic.product.domain.Channel;
import com.splic.product.domain.ProductVersion;
import com.splic.product.mapper.ChannelMapper;
import com.splic.product.service.ChannelService;
import com.splic.product.service.DeviceStatisService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.splic.common.annotation.Log;
import com.splic.common.enums.BusinessType;
import com.splic.product.domain.Product;
import com.splic.product.service.ProductService;
import com.splic.common.core.controller.BaseController;
import com.splic.common.core.domain.AjaxResult;
import com.splic.common.utils.poi.ExcelUtil;
import com.splic.common.core.page.TableDataInfo;

/**
 * 应用Controller
 * 
 * @author singe
 * @date 2022-01-04
 */
@Controller
@RequestMapping("/product/product")
public class ProductController extends BaseController
{
    private String prefix = "product/product";

    @Autowired
    private ProductService productServiceImpl;

    @Autowired
    private ChannelService channelServiceImpl;

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private DeviceStatisService deviceStatisServiceImpl;

    @RequiresPermissions("product:product:view")
    @GetMapping()
    public String product()
    {
        return prefix + "/list";
    }

    /**
     * 查询应用列表
     */
    @RequiresPermissions("product:product:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Product product)
    {
        startPageNoOrderBy();
        List<Product> list = productServiceImpl.selectProductList(product);
        List<Channel> channelList = channelServiceImpl.selectChannelList(null);
        Map<Long, String> map = new HashMap<>();
        for (Channel channel : channelList) {
            map.put(channel.getId(), channel.getName());
        }
        for (Product product1 : list) {
            String channel = product1.getChannel();
            if (StringUtils.isNotEmpty(channel)) {
                List<Long> channelArr = Arrays.stream(channel.split(",")).mapToLong(Long::valueOf).boxed().collect(Collectors.toList());
                String str;
                StringBuilder sb = new StringBuilder();
                if (channelArr.size() > 2) {
                    sb.append(map.get(channelArr.get(0)));
                    sb.append(",");
                    sb.append(map.get(channelArr.get(1)));
                    sb.append("...");
                    str = sb.toString();
                } else {
                    for (Long id :channelArr) {
                        sb.append(map.get(id));
                        sb.append(",");
                    }
                    str = sb.substring(0, sb.length() - 1);
                }
                product1.setChannel(str);
            }
            String phoneBrand = product1.getPhoneBrand();
            if (StringUtils.isNotEmpty(phoneBrand)) {
                String[] phoneBrandArr = phoneBrand.split(",");
                if (phoneBrandArr.length > 2) {
                    product1.setPhoneBrand(phoneBrand.substring(0, phoneBrand.indexOf(phoneBrandArr[2])) + "...");
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 新增应用
     */
    @GetMapping(value = { "/form/{id}", "/form" })
    public String form(@PathVariable(value = "id", required = false) Long id, ModelMap mmap)
    {
        if (StringUtils.isNotNull(id)){
            Product product = productServiceImpl.selectProductById(id);
            if (product != null) {
                String channel = product.getChannel();
                if (StringUtils.isNotEmpty(channel)) {
                    mmap.put("channelChecked", Arrays.stream(channel.split(",")).mapToLong(Long::valueOf).boxed().collect(Collectors.toList()));
                } else {
                    mmap.put("channelChecked", new ArrayList<Long>());
                }
                List<Channel> channelList = channelServiceImpl.selectChannelList(null);
                mmap.put("channelList", channelList);

                String phoneBrand = product.getPhoneBrand();
                if (StringUtils.isNotEmpty(phoneBrand)) {
                    mmap.put("phoneBrandChecked", Arrays.stream(phoneBrand.split(",")).collect(Collectors.toList()));
                } else {
                    mmap.put("phoneBrandChecked", new ArrayList<Long>());
                }
                List<String> phoneBrandList = new ArrayList<>();
                phoneBrandList.add("全部");
                phoneBrandList.addAll(deviceStatisServiceImpl.selectAddPhoneBrandList());
                mmap.put("phoneBrandList", phoneBrandList);

                mmap.put("product", product);
            } else {
                mmap.put("product", new Product());
            }
        }else{
            mmap.put("product", new Product());
        }
        return prefix + "/form";
    }


    /**
     * 新增保存应用
     */
    @RequiresPermissions("product:product:edit")
    @Log(title = "应用", businessType = BusinessType.INSERT)
    @PostMapping("/saveOrUpdate")
    @ResponseBody
    public AjaxResult saveOrUpdate(Product product)
    {
        if (product.getChannels() != null && product.getChannels().size() > 0) {
            String channel = product.getChannels().stream().map(String::valueOf).collect(Collectors.joining(","));
            product.setChannel(channel);
        } else {
            product.setChannel("");
        }
        if (product.getPhoneBrands() != null && product.getPhoneBrands().size() > 0) {
            String phoneBrand = String.join(",", product.getPhoneBrands());
            product.setPhoneBrand(phoneBrand);
        } else {
            product.setPhoneBrand("");
        }
        return toAjax(productServiceImpl.saveOrUpdate(product));
    }

    /**
     * 删除
     */
    @RequiresPermissions("product:product:remove")
    @Log(title = "应用", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(Long id)
    {
        return toAjax(productServiceImpl.deleteById(id));
    }


    /**
     * 导出应用列表
     */
    @RequiresPermissions("product:product:export")
    @Log(title = "应用", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Product product)
    {
        List<Product> list = productServiceImpl.selectProductList(product);
        ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
        return util.exportExcel(list, "应用数据");
    }

    /**
     * 上线渠道列表
     */
    @GetMapping(value = { "/channelList/{id}"})
    public String channelList(@PathVariable(value = "id", required = false) Long id, ModelMap mmap)
    {
        mmap.put("id", id);
        mmap.put("item", 0);
        return prefix + "/namelist";
    }

    /**
     * 上线渠道列表
     */
    @PostMapping(value = { "/getChannelList"})
    @ResponseBody
    public TableDataInfo getChannelList(Long id)
    {
        List<Channel> nameList = new ArrayList<>();
        Product product = productServiceImpl.selectProductById(id);
        if (product != null) {
            String channel = product.getChannel();
            if (StringUtils.isNotEmpty(channel)) {
                List<Long> ids = Arrays.stream(channel.split(",")).mapToLong(Long::valueOf).boxed().collect(Collectors.toList());
                Channel channel1 = new Channel();
                channel1.setIds(ids);
                startPage();
                nameList = channelMapper.selectNameList(ids);
            }
        }
        return getDataTable(nameList);
    }

    /**
     * 上线品牌列表
     */
    @GetMapping(value = { "/phoneBrandList/{id}"})
    public String phoneBrandList(@PathVariable(value = "id", required = false) Long id, ModelMap mmap)
    {
        mmap.put("id", id);
        mmap.put("item", 1);
        return prefix + "/namelist";
    }

    /**
     * 上线品牌列表
     */
    @PostMapping(value = { "/getPhoneBrandList"})
    @ResponseBody
    public TableDataInfo getPhoneBrandList(Long id)
    {
        List<Map<String, Object>> nameList = new ArrayList<>();
        Product product = productServiceImpl.selectProductById(id);
        if (product != null) {
            String phoneBrand = product.getPhoneBrand();
            if (StringUtils.isNotEmpty(phoneBrand)) {
                List<String> strList = Arrays.stream(phoneBrand.split(",")).collect(Collectors.toList());
                int count = 1;
                for (String str : strList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", count);
                    map.put("name", str);
                    nameList.add(map);
                    count ++;
                }
            }
        }
        return getDataTable(nameList);
    }

    /**
     * 版本列表
     */
    @RequiresPermissions("product:product:view")
    @GetMapping("versionList")
    public String productVersion(ModelMap mmap)
    {
        List<Product> productList = productServiceImpl.selectProductList(null);
        mmap.put("productList",productList);
        return prefix + "/versionList";
    }


//    @GetMapping(value = { "/versionList/{id}"})
//    public String versionList(@PathVariable(value = "id", required = false) Long id, ModelMap mmap)
//    {
//        mmap.put("productId", id);
//        return prefix + "/versionList";
//    }

    /**
     * 版本列表
     */
    @PostMapping(value = { "/getVersionList"})
    @ResponseBody
    public TableDataInfo getVersionListList(Long productId)
    {
        startPageNoOrderBy();
        List<Map<String, Object>> resultMap = productServiceImpl.selectProductVersionById(productId);
        return getDataTable(resultMap);
    }

    /**
     * 新增版本
     */
    @GetMapping(value = { "/version/form",  "/version/form/{id}"})
    public String versionForm(@PathVariable(value = "id", required = false) Long id, ModelMap mmap)
    {
        List<Product> productList = productServiceImpl.selectProductList(null);
        mmap.put("productList",productList);
        if (id != null) {
            mmap.put("productVersion", productServiceImpl.selectVersionByVersionId(id));
        } else {
            mmap.put("productVersion", new ProductVersion());
        }
        return prefix + "/versionForm";
    }


    /**
     * 新增保存版本
     */
    @RequiresPermissions("product:product:version:add")
    @Log(title = "版本", businessType = BusinessType.INSERT)
    @PostMapping("/version/saveOrUpdate")
    @ResponseBody
    public AjaxResult saveOrUpdateVersion(ProductVersion version)
    {
        return toAjax(productServiceImpl.saveOrUpdateVersion(version));
    }

    /**
     * 删除版本
     */
    @RequiresPermissions("product:product:version:remove")
    @Log(title = "版本", businessType = BusinessType.DELETE)
    @PostMapping("/version/remove")
    @ResponseBody
    public AjaxResult removeVersion(String ids)
    {
        if (StringUtils.isNotEmpty(ids)) {
            List<String> idsList = Arrays.stream(ids.split(",")).collect(Collectors.toList());
            return toAjax(productServiceImpl.deleteVersion(idsList));
        } else {
            return toAjax(1);
        }
    }
}
